AWS CDK でパラメーターストアをクロスリージョンで取得するカスタムリソースを作ってみた

AWS CDK でパラメーターストアをクロスリージョンで取得するカスタムリソースを作ってみた

Clock Icon2024.07.15

こんにちは、製造ビジネステクノロジー部の若槻です。

今回は、AWS CDKAWS Systems Manager Parameter Store をクロスリージョンで取得するカスタムリソースを作ってみたのでご紹介します。

やってみた

カスタムリソースの実装

次のように AWS CDK のcustom_resources.AwsCustomResourceクラスを使用したカスタムリソースのコンストラクトを作成します。

指定したリージョンから指定した名前のパラメーターをSSM:getParameterアクションを使用して取得するというものです。

lib/cross-region-get-parameter-custom-resource.ts
import { custom_resources } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class CrossRegionGetParameter extends Construct {
  public readonly parameterValue: string;

  constructor(
    scope: Construct,
    id: string,
    props: {
      readonly parameterName: string;
      readonly region: string;
    }
  ) {
    super(scope, id);

    const getParameter = new custom_resources.AwsCustomResource(
      this,
      'GetParameterCustomResource',
      {
        onUpdate: {
          service: 'SSM',
          action: 'getParameter',
          parameters: {
            Name: props.parameterName,
          },
          physicalResourceId: custom_resources.PhysicalResourceId.of(
            props.parameterName
          ),
          region: props.region,
        },
        policy: custom_resources.AwsCustomResourcePolicy.fromSdkCalls({
          resources: custom_resources.AwsCustomResourcePolicy.ANY_RESOURCE,
        }),
        installLatestAwsSdk: false,
      }
    );

    this.parameterValue = getParameter.getResponseField('Parameter.Value');
  }
}

カスタムリソースを使ってみる

取得対象のパラメータを us-east-1 リージョンに作成しておきます。

aws ssm put-parameter --name sampleVirginiaParameter --type String --value "Hello from Virginia" --region us-east-1

前述のカスタムリソースを使う実装を CDK スタックで行います。

lib/cdk-sample-stack.ts
import { Stack, CfnOutput } from 'aws-cdk-lib';
import { Construct } from 'constructs';

import { CrossRegionGetParameter } from './cross-region-get-parameter-custom-resource';

export class CdkSampleStack extends Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // カスタムリソースを使って、us-east-1 リージョンのパラメータストアを取得する
    const sampleVirginiaParameter = new CrossRegionGetParameter(
      this,
      'SampleVirginiaParameter',
      {
        parameterName: 'sampleVirginiaParameter',
        region: 'us-east-1',
      }
    );

    // 取得したパラメータの値を確認
    new CfnOutput(this, 'SampleVirginiaParameterValueOutput', {
      value: sampleVirginiaParameter.parameterValue,
    });
  }
}

取得対象のパラメーターストアと異なる ap-northeast-1 リージョンで CDK スタックをデプロイします。するとパラメーターストアの値が取得できることが確認できます。

$ npm run deploy

> cdk_sample_app@0.1.0 deploy
> cdk deploy --require-approval never --method=direct

✨  Synthesis time: 2.93s

CdkSampleStack:  start: Building e4ea0253cc86c2c55a7b1f7ed734d91c8db2f5e8f8477c3a5a01690557a76c01:current_account-current_region
CdkSampleStack:  success: Built e4ea0253cc86c2c55a7b1f7ed734d91c8db2f5e8f8477c3a5a01690557a76c01:current_account-current_region
CdkSampleStack:  start: Publishing e4ea0253cc86c2c55a7b1f7ed734d91c8db2f5e8f8477c3a5a01690557a76c01:current_account-current_region
CdkSampleStack:  success: Published e4ea0253cc86c2c55a7b1f7ed734d91c8db2f5e8f8477c3a5a01690557a76c01:current_account-current_region
CdkSampleStack: deploying... [1/1]
CdkSampleStack: updating stack...

 ✅  CdkSampleStack

✨  Deployment time: 11.61s

Outputs:
CdkSampleStack.SampleVirginiaParameterValueOutput = Hello from Virginia
Stack ARN:
arn:aws:cloudformation:ap-northeast-1:XXXXXXXXXXXX:stack/CdkSampleStack/bdcdf7a0-3443-11ef-8401-06d40bdb5af9

✨  Total time: 14.54s

installLatestAwsSdk プロパティは false に設定した方が良さそう

今回紹介したカスタムリソースのコードでは、custom_resources.AwsCustomResourceinstallLatestAwsSdk プロパティを明示的に false に指定しています。

指定しない場合は次のような警告が表示されます。

npm run deploy

> cdk_sample_app@0.1.0 deploy
> cdk deploy --require-approval never --method=direct

[Warning at /CdkSampleStack/SampleVirginiaParameter/GetParameterCustomResource] installLatestAwsSdk was not specified, and defaults to true. You probably do not want this. Set the global context flag '@aws-cdk/customresources:installLatestAwsSdkDefault' to false to switch this behavior off project-wide, or set the property explicitly to true if you know you need to call APIs that are not in Lambda's built-in SDK version. [ack: @aws-cdk/custom-resources:installLatestAwsSdkNotSpecified]

✨  Synthesis time: 3.16s

ドキュメントによると、カスタムリソースとなる Lambda 関数に最新バージョンの SDK である AWS SDK for v3 がインストールされるとのこと。

To make sure that the newest API calls are available the latest AWS SDK v3 is installed in the Lambda function implementing the custom resource. The installation takes around 60 seconds. If you prefer to optimize for speed, you can disable the installation by setting the installLatestAwsSdk prop to false.

(日本語訳)
最新の API 呼び出しが利用できるように、カスタム リソースを実装する Lambda 関数に最新の AWS SDK v3 がインストールされます。インストールには約 60 秒かかります。速度を最適化したい場合は、installLatestAwsSdk プロパティを false に設定してインストールを無効にすることができます。

Lambda 関数とはカスタムリソースを実装したスタック内に作成するこちらのことですね。

しかし、この Lambda 関数のランタイムは Node.js 20.x であるため、既定で AWS SDK v3 がインストールされます。よってビルド速度を最適化できるように installLatestAwsSdk プロパティは false に設定した方が良さそうです。

カスタムリソースを使えば API の呼び出しは簡単に実装できる

下記にある通り、AWS CDK ではカスタムリソースを使えば単純な API の呼び出しだけなら簡単に実装することができます。今回はそれを活用しての AWS Systems Manager Parameter Store の値取得の実装でした。
https://dev.classmethod.jp/articles/create-custom-resources-with-aws-cdk-without-using-lambda-functions/

以上

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.